import React, {useState} from 'react'
import 'antd/dist/antd.css'
import {Card,Input,Icon,Button,Spin, message} from 'antd'
import '../static/css/login.css'
import axios from 'axios'
import servicePath from '../config/apiUrl'

function Login(props){

    const [userName,setUserName] = useState('')
    const [password,setpassword] = useState('')
    const [isLoading,setisLoading] = useState(false)

    const checkLogin =() =>{
        setisLoading(true)
        if(!userName){
            message.error('用户名不能为空！')
            setisLoading(false)
            return false
        }else if(!password){
            message.error('密码不能为空！')
            setisLoading(false)
            return false
        }
        let dataProps = {
            'userName': userName,
            'password': password
        }

        axios({
            method: 'POST',
            url: servicePath.checkLogin,
            data: dataProps,
            withCredentials: true
        }).then(
            res => {
                setisLoading(false)
                if(res.data.data == "登录成功"){
                    localStorage.setItem('openId',res.data.openId)
                    props.history.push('/adminIndex')
                }else{
                    message.error('用户名密码错误！')
                }
            }
        ).catch(
            error => {
                setisLoading(false)
                message.error('服务错误！')
            }
        )
    }


    return (
        <div className="login-div">
            <Spin tip='Loading...' spinning={isLoading}>
                <Card title="DOUBLEBUG blog system" bordered={true} style={{width: 400}}>
                    <Input 
                        id="userName"
                        size="large"
                        placeholder="Enter your userName"
                        prefix={<Icon type="user" style={{color:'rgba(0,0,0,.25'}} />}
                        onChange={(e)=>{setUserName(e.target.value)}}
                    />
                    <br />
                    <br />
                    <Input.Password
                        id="password"
                        size="large"
                        placeholder="Enter your password"
                        prefix={<Icon type="key" style={{color:'rgba(0,0,0,.25'}} />}
                        onChange={(e)=>{setpassword(e.target.value)}}
                    />
                    <br />
                    <br />
                    <Button type="primary" size="large" block onClick={checkLogin}>Login in</Button>
                </Card>
            </Spin>
        </div>
    )
}

export default Login
